package com.jinlejia.erp.ui.customer;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.ContractAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivityRecordCustomer1Binding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.common.SourceTypeDialog;
import com.jinlejia.erp.ui.common.TagsDialog;
import com.jinlejia.erp.ui.mine.client.ContactsListActivity;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.RegexUtils;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 录客源第一步
 */
public class RecordCustomer1Activity extends AppCompatActivity {

    private JSONObject jsonObject = new JSONObject();

    private String sex ;
    private String dType ;
    private String linkSex ;

    private TagsDialog tagsDialog;
    private ArrayList<String> tagList = new ArrayList<>();
    private JSONObject customerData;
    private String customerType;
    private boolean isEdit = false;
    private ArrayList<Map<String, Object>> sourceData = new ArrayList<>();
    private String sourceType, source;
    private JSONArray contactList;
    private ContractAdapter contractAdapter;
    private String telID;
    private ProgressDialog progressDialog;

    private ActivityRecordCustomer1Binding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_record_customer1);
        binding.setEvent(this);
        EventBus.getDefault().register(this);
        EventBus.getDefault().registerSticky(this);
        initView();
        getTags();
        getSource();
        customerType = getIntent().getStringExtra("type");
    }

    private void initView() {
        progressDialog = new ProgressDialog(this,"请稍等...");
        //性别
        binding.rgGender.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.male_radio:
                    sex = "1";
                    break;
                case R.id.female_radio:
                    sex = "0";
                    break;
                default:
                    break;
            }
        });
        //类型
        binding.rgDelegateType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.buyradio:
                    dType = "1";
                    customerType = "shs";
                    break;
                case R.id.magebrug_radio:
                    dType = "0";
                    customerType = "rent";
                    break;
                default:
                    break;
            }
        });
        //联系人性别
        binding.rgLinkGender.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.male_link_radio:
                    linkSex = "1";
                    break;
                case R.id.female_link_radio:
                    linkSex = "0";
                    break;
                default:
                    break;
            }
        });
        binding.contractRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.contractRecycler.setHasFixedSize(true);
        binding.contractRecycler.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        contractAdapter = new ContractAdapter(new ArrayList<>());
        binding.contractRecycler.setAdapter(contractAdapter);

        binding.ratingbar.setOnRatingBarChangeListener((ratingBar, rating, fromUser) -> {
            if (rating < 1)
                ratingBar.setRating(1);
        });
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.next:
                //从通讯录添加
                if (!isEdit){
                    Intent intent = new Intent(RecordCustomer1Activity.this, ContactsListActivity.class);
                    startActivityForResult(intent,119);
                }
                break;
            case R.id.bt_next:
                if (isEdit) {
                    //编辑
                    editData();
                } else {
                    putData();
                }
                break;
            case R.id.bt_add_phone:
                //添加联系方式
                ArrayList<Map<String, Object>> data = contractAdapter.getData();
                Map<String, Object> map = new HashMap<>();
                map.put("typeName", "手机");
                map.put("typeCode", 1);
                if (contractAdapter.mData.size() < 2) {
                    data.add(map);
                    contractAdapter.setData(data);
                } else {
                    CustomToast.showToast(this, "最多添加三条联系方式", 1500);
                }
                break;
            case R.id.delegate_from:
                final SourceTypeDialog sourceTypeDialog = new SourceTypeDialog(RecordCustomer1Activity.this, sourceData);
                sourceTypeDialog.show();
                sourceTypeDialog.setOnSelectedListener((source1Map, source2map) -> {
                    sourceType = source1Map.get("valuel").toString();
                    source = source2map.get("valuel").toString();
                    binding.delegateFrom.setText(source1Map.get("valueName").toString() + " - " + source2map.get("valueName").toString());
                    sourceTypeDialog.dismiss();
                });
                break;
            case R.id.tags:
                tagsDialog = new TagsDialog(RecordCustomer1Activity.this, tagList);
                tagsDialog.show();
                tagsDialog.setOnSelectListener(str -> binding.tags.setText(str));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if( resultCode == RESULT_OK && requestCode == 119 ){
            String name = data.getStringExtra("name");
            String tel = data.getStringExtra("tel");
            binding.etName.setText(name);
            binding.etPhone.setText(tel);
        }else if( resultCode == RESULT_OK && requestCode == 100 ){
            setResult(RESULT_OK,data);
            finish();
        }
    }

    private void editData() {
        customerData.put("name", binding.etName.getText().toString());
        //性别（int 1=男，0=女）
        customerData.put("sex", sex);
        customerData.put("tel", binding.tvPhone.getText().toString());
        //（1=求购，0=求组）
        customerData.put("type", dType);
        //委托类型 一级
        customerData.put("sourceType", sourceType);
//        //委托来源二级
        customerData.put("source", source);
        //标签（用“;”分开的字符串）
        customerData.put("tags", binding.tags.getText().toString());
        //购房意向(int）
        customerData.put("level", (int) binding.ratingbar.getRating());
        //联系人
        JSONObject linkObject = new JSONObject();
        if( !TextUtils.isEmpty( binding.etLinkmanName.getText().toString() ) )
            linkObject.put("name", binding.etLinkmanName.getText().toString());
        if( !TextUtils.isEmpty( linkSex ) )
            linkObject.put("sex", linkSex);
        if( !TextUtils.isEmpty( binding.etLinkPhone.getText().toString() ) )
            linkObject.put("tel", binding.etLinkPhone.getText().toString());
        if ( linkObject.size() == 3 ) {
            customerData.put("customerContact", linkObject);
        }
        //联系方式
        contactList = new JSONArray();
        JSONArray Telstr = new JSONArray();
        JSONObject js = new JSONObject();
        js.put("type", "1");
        js.put("tel", binding.tvPhone.getText().toString());
        js.put("id", telID);
        contactList.add(js);
        String newTelStr = "", c1 = "", c2 = "";
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < contractAdapter.mData.size(); i++) {
            //更多联系方式
            Map<String, Object> map = contractAdapter.mData.get(i);
            JSONObject j = new JSONObject();
            j.put("type", map.get("typeCode"));
            j.put("tel", map.get("number"));
            if (!map.containsKey("id")) {
                jsonArray.add(j);
            } else {
                newTelStr = newTelStr.concat(";").concat(map.get("number").toString());
                if (i == 0) {
                    c1 = map.get("number").toString();
                } else {
                    c2 = map.get("number").toString();
                }
            }
            contactList.add(j);
        }
        customerData.put("customerContactTypeList", contactList.toString());

        if (TextUtils.isEmpty(customerData.getString("name"))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "请输入姓名", 1500);
        }
        else if (!TextUtils.isEmpty(c1) && !RegexUtils.isMobileExact(c1) && !RegexUtils.isTel(c1)) {
            CustomToast.showToast(RecordCustomer1Activity.this, "手机号格式错误", 1500);
        } else if (!TextUtils.isEmpty(c2) && !RegexUtils.isMobileExact(c2) && !RegexUtils.isTel(c2)) {
            CustomToast.showToast(RecordCustomer1Activity.this, "手机号格式错误", 1500);
        } else if (binding.tvPhone.getText().toString().equals(c1) || binding.tvPhone.getText().toString().equals(c2) || (c1.equals(c2) && !TextUtils.isEmpty(c1))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "输入的手机号相同", 1500);
        }else if ( linkObject.size() >0 && linkObject.size()<3 ){
            if(TextUtils.isEmpty(linkObject.getString("name"))){
                CustomToast.showToast(RecordCustomer1Activity.this, "请输入联系人姓名", 1500);
            }else if(TextUtils.isEmpty(linkObject.getString("sex"))){
                CustomToast.showToast(RecordCustomer1Activity.this, "请输入联系人性别", 1500);
            }else if(TextUtils.isEmpty(linkObject.getString("tel"))){
                CustomToast.showToast(RecordCustomer1Activity.this, "请输入联系人电话", 1500);
            }
        }else if (!TextUtils.isEmpty(binding.etLinkPhone.getText().toString()) && !RegexUtils.isMobileExact(binding.etLinkPhone.getText().toString())) {
            CustomToast.showToast(RecordCustomer1Activity.this, "联系人手机号格式错误", 1500);
        } else if (TextUtils.isEmpty(customerData.getString("sourceType"))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "请选择委托来源", 1500);
        } else {
            JSONObject object = new JSONObject();
            object.put("csCode", customerData.get("csCode"));
            object.put("customerTypeList",jsonArray.toJSONString());
            if( jsonArray.size()>0 ){
                editValidate(object);
            }  else{
                EventBus.getDefault().postSticky(customerData, "TAG_EDIT_STEP1");
                Intent eIntent = new Intent(RecordCustomer1Activity.this, RecordCustomer2Activity.class);
                eIntent.putExtra("type", customerType);
                startActivityForResult(eIntent,100);
            }

        }
    }

    private void putData() {
        jsonObject.put("name", binding.etName.getText().toString());
        //性别（int 1=男，0=女）
        jsonObject.put("sex", sex);
        jsonObject.put("tel", binding.etPhone.getText().toString());

        //（1=求购，0=求组）
        jsonObject.put("type", dType);
        //委托类型 一级
        jsonObject.put("sourceType", sourceType);
        //委托来源二级
        jsonObject.put("source", source);
        //标签（用“;”分开的字符串）
        if (!TextUtils.isEmpty(binding.tags.getText().toString()))
            jsonObject.put("tags", binding.tags.getText().toString());
        //购房意向(int）
        jsonObject.put("level", (int) binding.ratingbar.getRating());
        //联系人
        JSONObject linkObject = new JSONObject();
        if( !TextUtils.isEmpty( binding.etLinkmanName.getText().toString() ) )
        linkObject.put("name", binding.etLinkmanName.getText().toString());
        if( !TextUtils.isEmpty( linkSex ) )
        linkObject.put("sex", linkSex);
        if( !TextUtils.isEmpty( binding.etLinkPhone.getText().toString() ) )
        linkObject.put("tel", binding.etLinkPhone.getText().toString());
        if ( linkObject.size() == 3 ) {
            jsonObject.put("customerContact", linkObject);
        }

        //联系方式
        contactList = new JSONArray();
        JSONObject js = new JSONObject();
        js.put("type", "2");
        js.put("tel", binding.etPhone.getText().toString());
        contactList.add(js);
        String contact1 = "", contact2 = "";
        for (int i = 0; i < contractAdapter.mData.size(); i++) {
            //更多联系方式
            Map<String, Object> map = contractAdapter.mData.get(i);
            JSONObject j = new JSONObject();
            j.put("type", map.get("typeCode"));
            j.put("tel", map.get("number"));
            if (map.containsKey("number") && !TextUtils.isEmpty(map.get("number").toString()))
                contactList.add(j);
            if (i == 0) {
                if (null != map.get("number"))
                    contact1 = (String) map.get("number");
            } else if (i == 1) {
                if (null != map.get("number"))
                    contact2 = (String) map.get("number");
            }
        }
        jsonObject.put("customerContactTypeList", contactList.toString());

        if (TextUtils.isEmpty(jsonObject.getString("name"))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "请输入姓名", 1500);
        }else  if (TextUtils.isEmpty(jsonObject.getString("sex"))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "请选择性别", 1500);
        }else if (TextUtils.isEmpty(jsonObject.getString("tel"))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "请输入手机号", 1500);
        } else if (!RegexUtils.isMobileExact(binding.etPhone.getText().toString())) {
            CustomToast.showToast(RecordCustomer1Activity.this, "手机号格式错误", 1500);
        } else if (!TextUtils.isEmpty(contact1) && !RegexUtils.isMobileExact(contact1) && !RegexUtils.isTel(contact1)) {
            CustomToast.showToast(RecordCustomer1Activity.this, "手机号格式错误", 1500);
        } else if (!TextUtils.isEmpty(contact2) && !RegexUtils.isMobileExact(contact2) && !RegexUtils.isTel(contact2)) {
            CustomToast.showToast(RecordCustomer1Activity.this, "手机号格式错误", 1500);
        } else if (binding.etPhone.getText().toString().equals(contact1) || binding.etPhone.getText().toString().equals(contact2) || (contact1.equals(contact2) && !TextUtils.isEmpty(contact1))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "输入的手机号相同", 1500);
        } else if ( linkObject.size() >0 && linkObject.size()<3 ){
            if(TextUtils.isEmpty(linkObject.getString("name"))){
                CustomToast.showToast(RecordCustomer1Activity.this, "请输入联系人姓名", 1500);
            }else if(TextUtils.isEmpty(linkObject.getString("sex"))){
                CustomToast.showToast(RecordCustomer1Activity.this, "请输入联系人性别", 1500);
            } else if(TextUtils.isEmpty(linkObject.getString("tel"))){
                CustomToast.showToast(RecordCustomer1Activity.this, "请输入联系人电话", 1500);
            }
        }else if (!TextUtils.isEmpty(binding.etLinkPhone.getText().toString()) && !RegexUtils.isMobileExact(binding.etLinkPhone.getText().toString()) && !RegexUtils.isTel(binding.etLinkPhone.getText().toString())) {
            CustomToast.showToast(RecordCustomer1Activity.this, "联系人手机号格式错误", 1500);
        }else if (TextUtils.isEmpty(jsonObject.getString("type"))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "请选择委托类型", 1500);
        } else if (TextUtils.isEmpty(jsonObject.getString("sourceType"))) {
            CustomToast.showToast(RecordCustomer1Activity.this, "请选择委托来源", 1500);
        } else {
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < contactList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("contactType", ((JSONObject) contactList.get(i)).get("type"));
                jsonObject.put("tel", ((JSONObject) contactList.get(i)).get("tel"));
                jsonArray.add(jsonObject);
            }
            Validate(jsonArray);
        }

    }

    /**
     * 获取tag列表
     */
    private void getTags() {
        OkHttpUtils.get()
                .url(ApiConfig.TAGS_LIST)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(RecordCustomer1Activity.this, response)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            //数据列表
                            tagList = JSON.parseObject(data.toString(), new TypeReference<ArrayList<String>>() {
                            });
                            if (null != tagsDialog)
                                tagsDialog.setData(tagList);
                        }
                    }
                });
    }

    /**
     * 获取委托来源列表
     */
    private void getSource() {
        OkHttpUtils.get()
                .url(ApiConfig.SOURCE_CUSTOMER)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(RecordCustomer1Activity.this, response)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            sourceData = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (!TextUtils.isEmpty(sourceType)) {
                                binding.delegateFrom.setText(getSource1(sourceType) + " - " + source);
                            }
                        }
                    }
                });
    }

    private String getSource1(String str) {
        for (Map<String, Object> map : sourceData) {
            if (map.get("valuel").toString().equals(str)) {
                return map.get("valueName").toString();
            }
        }
        return "";
    }

    private void Validate(JSONArray array) {
        progressDialog.show();
        String url = "";
        if (jsonObject.get("type").toString().equals("1")) {
            url = ApiConfig.CUSTOMER_SHS_VALIDATE;
        } else {
            url = ApiConfig.CUSTOMER_RENT_VALIDATE;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(array.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                        call.cancel();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(RecordCustomer1Activity.this, response)) {
                            EventBus.getDefault().postSticky(jsonObject, "TAG_RC_STEP1");
                            startActivityForResult(new Intent(RecordCustomer1Activity.this, RecordCustomer2Activity.class),100);
                        }
                    }
                });
    }

    private void editValidate(JSONObject object) {
        progressDialog.show();
        String url = "";
        if (customerData.get("type").toString().equals("1")) {
            url = ApiConfig.CUSTOMER_SHS_EDIT_VALIDATE;
        } else {
            url = ApiConfig.CUSTOMER_RENT_EDIT_VALIDATE;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                        call.cancel();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(RecordCustomer1Activity.this, response)) {
                            EventBus.getDefault().postSticky(customerData, "TAG_EDIT_STEP1");
                            Intent eIntent = new Intent(RecordCustomer1Activity.this, RecordCustomer2Activity.class);
                            eIntent.putExtra("type", customerType);
                            startActivity(eIntent);
                        }
                    }
                });
    }

    @Subscriber(tag = "TAG_ADD_TAG_SECCESS")
    private void tagSuccess(String s) {
        getTags();
    }

    @Subscriber(tag = "TAG_EDIT_CUSTOMER")
    private void cData(JSONObject object) {
        EventBus.getDefault().removeStickyEvent(object.getClass(), "TAG_EDIT_CUSTOMER");
        customerData = object;
        isEdit = true;
        binding.next.setVisibility(View.GONE);
        binding.etName.setText(object.getString("name"));
        //性别
        if (object.getIntValue("sex") == 0) {
            binding.femaleRadio.setChecked(true);
        } else {
            binding.maleRadio.setChecked(true);
        }
        //手机
        binding.tvPhone.setText(object.getString("tel"));
        binding.tvPhone.setVisibility(View.VISIBLE);
        binding.etPhone.setVisibility(View.GONE);
        //联系方式
        if (object.containsKey("customerContactTypeList")) {
            ArrayList<Map<String, Object>> list = JSON.parseObject(object.get("customerContactTypeList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
            });
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                if (map.get("tel").equals(object.get("tel"))) {
                    telID = map.get("id").toString();
                    list.remove(map);
                }
            }
            contractAdapter.setData(list);
        }

        //联系人
        if (object.containsKey("customerContact")) {
            binding.etLinkmanName.setText(object.getJSONObject("customerContact").getString("name"));
            if (object.getJSONObject("customerContact").getIntValue("sex") == 0) {
                binding.femaleLinkRadio.setChecked(true);
            } else {
                binding.maleLinkRadio.setChecked(true);
            }
            binding.etLinkPhone.setText(object.getJSONObject("customerContact").getString("tel"));
        }
        //委托类型
        if (customerType.equals("sale")) {
            binding.buyradio.setChecked(true);
            customerData.put("type", 1);
        } else {
            binding.magebrugRadio.setChecked(true);
            customerData.put("type", 0);
        }
        binding.magebrugRadio.setClickable(false);
        binding.buyradio.setClickable(false);
        //委托来源
        sourceType = object.getString("sourceType");
        source = object.getString("source");
        if (sourceData.size() > 0) {
            binding.delegateFrom.setText(getSource1(sourceType) + " - " + object.getString("source"));
        }

        //标签
        if (object.containsKey("tags")) {
            JSONArray tagArr = JSON.parseArray(object.getString("tags"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < tagArr.size(); i++) {
                sb = sb.append(";").append(tagArr.get(i).toString());
            }
            binding.tags.setText(sb.toString().replaceFirst(";", ""));
        }

        //意愿
        binding.ratingbar.setRating(object.getIntValue("level"));


    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
